var userInf;
var ownerInfos;

apiready = function() {
	$api.getUserInf(function(user) {
		$api.replaceHtml($("body"), user);
		userInf = user;
	});
};

//发送验证码按钮
$("#btnBrown").on('click', function() {
	var phoneNum = $("#phone").val();
	$api.verifyPhone(phoneNum, function(phone) {
		$api.do_post('/api/property/verify/send/msg', {
			body: JSON.stringify({
				account: userInf.account,
				phone: phone
			})
		}, function(result) {
			//发送验证码成功后
			if (result.code === 0) {
				$api.btnWait("#btnBrown");
				$api.crateDom('_verifyFcItem.html', result.ownerInfos, function(resultHtml) {
					ownerInfos = result.ownerInfos;
					$('#fcrq').html(resultHtml);
				})
			} else {
				$api.toastMsg(result.msg);
			}
		})
	});
});


//验证按钮
$("#btnVerify").on('click', function() {
	if (!ownerInfos) {
		$api.toastMsg("请先发送验证码");
		return;
	}



	var pNum = $("#phone").val();
	$api.verifyPhone(pNum, function(phoneNum) {
		//获取选择的房产id
		var fcrqId = $("#fcrq").val();
		var ownerInfo;

		for (var i = 0; i < ownerInfos.length; i++) {
			if (ownerInfos[i]._id === fcrqId) {
				ownerInfo = ownerInfos[i];
			}
		}

		if (!ownerInfo) {
			$api.toastMsg("请选择房产");
			return;
		}

		var param = {
			account: userInf.account,
			mobile: userInf.account,
			zycode: ownerInfo.code,
			ownerName: ownerInfo.name,
			ownerMobile: pNum,
			residential: ownerInfo.residential,
			unitName: ownerInfo.unitName,
			roomNumber: ownerInfo.roomNumber,
			vCode: $("#msgCode").val(),
		}

		for (var v in param) {
			console.error(v + " : " + param[v]);
		}

		if (!param.vCode) {
			$api.toastMsg("请输入4位长度的验证码");
			return;
		}
		$api.do_post("/api/property/verify/passed", {
			body: JSON.stringify(param)
		}, function(result) {
			console.error("code:" + result.code + "  msg:" + result.msg);
			if (result.code == '0') {
				//从网上更新一次用户数据
				$api.do_post('/api/commuser/info', {
					body: $api.jsonToStr({
						id: userInf._id
					})
				}, function(ret) {
					$api.setUserInf(ret.entity);
					alert("绑定成功");
					api.closeWin();
				});
			} else {
				console.error("code:" + result.code + "  msg:" + result.msg);
			}
		})

	})
})